package com.xm;

import lombok.extern.slf4j.Slf4j;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class RetryService {

    @Retryable(
        value = { CustomException.class },  // 指定要重试的异常类型
        maxAttempts = 3,                    // 最大重试次数
        recover = "recover2",                // 重试失败的处理方法
        backoff = @Backoff(delay = 2000)    // 重试间隔
    )
    public String myMethod() throws CustomException {
        boolean flag = true;
        log.info("模拟业务");
        // 处理业务，处理异常抛出自定义异常
        if(flag) {
            throw new CustomException("模拟业务异常");
        }else {
            // 正常业务继续执行下一步流程
            return "模拟业务正常";
        }
    }

    /**
     * 自定义异常类
     *
     * @param
     * @return
     * @date 2024/10/9 15:20
     * @author lililiang
     */
    public static class CustomException extends Exception {
        public CustomException(String message) {
            super(message);
        }
    }



    @Recover
    public String recover(CustomException e) {
        // 处理重试失败后的逻辑，打印日志、发送警告等
        log.info("重试异常仍然为异常 {}", e.getMessage());
        return e.getMessage();
    }

    @Recover
    public String recover2(CustomException e) {
        // 处理重试失败后的逻辑，打印日志、发送警告等
        log.info("重试异常仍然为异常2 {}", e.getMessage());
        return e.getMessage();
    }

    @Recover
    public String recover3(CustomException e) {
        // 处理重试失败后的逻辑，打印日志、发送警告等
        log.info("重试异常仍然为异常3 {}", e.getMessage());
        return e.getMessage();
    }
}
